var sha1 = require('sha1');
var url = require('url');
var bodyParser = require('body-parser');
var fs = require('fs');
var config = require("./config");

var Token = config.Token;
var EncodingAESKey= config.EncodingAESKey;
var corpid = config.corpid;
var replay = require('./weixinReply');
var helper = require('./weixinHelper');

var Weixin = function(){
};

Weixin.prototype.service = function(req,res){
    var urlObj = url.parse(req.url);
    console.log("\n urlObj.pathname" + urlObj.pathname);
    if(req.method == "GET" && urlObj.pathname == "/wechat/urlCheck"){
        this.checkSignature(req,res);
    }else if(urlObj.pathname == "/wechat/urlCheck"){
        this.onMessage(req,res);
    }else if(urlObj.pathname == "/wechat/oauth"){
        /**
         *
         * http://x5.justep.com/wechat/oauth?
         *  state=STATE&
         *  code=D7SffsEO30FgnDdp6DPzZOzdbUkAzsAotqMTKOIinHnkc29NldhoKSIQl9HH8qaP
            https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE&agentid=AGENTID

        var code = req.query.code;
        https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE&agentid=AGENTID
        res.writeHead(200, {'Content-Type': 'text/plain' });
        res.end("oauth test");
         */
        debugger;
        var code = req.query.code;
        helper.getUserInfo(code,function(error,userID){
            /**
             * 通过https 联系wechat 获取userID（用户名）
             * 然后登陆x5
             * http://192.168.1.49:8080/x5/UI2/portal/oauth2.j
             *
             1.msg_signature是签名，用于验证调用者的合法性。

             2.EncodingAESKey用于消息体的加密，长度固定为43个字符，
                从a-z, A-Z, 0-9共62个字符中选取，是AESKey的Base64编码。
                解码后即为32字节长的AESKey

             3.AESKey=Base64_Decode(EncodingAESKey + “=”)，是AES算法的密钥，
                长度为32字节。AES采用CBC模式，数据采用PKCS#7填充；
                IV初始向量大小为16字节，取AESKey前16字节。

             4.msg为消息体明文，格式为XML

             5.msg_encrypt = Base64_Encode( AES_Encrypt[random(16B) + msg_len(4B) + msg + $CorpID] )，
                是对明文消息msg加密处理后的Base64编码。
                其中random为16字节的随机字符串；
                msg_len为4字节的msg长度，网络字节序；
                msg为消息体明文；
                $CorpID为企业号的标识
             *
             */
            console.log("userID:" + userID);
            res.writeHead(200, {'Content-Type': 'text/html' });
            if(userID == "007slm"){
                if(req.query.state == "daiban"){
                    res.end("<script>location.href='http://192.168.1.49:8080/x5/UI2/portal/Oauth2.j?username=system&state=daiban'</script>");
                }else{
                    res.end("<script>location.href='http://192.168.1.49:8080/x5/UI2/portal/Oauth2.j?username=system&state=login'</script>");
                }
            }else if(userID == "demo"){
                res.end("<script>location.href='http://192.168.1.49:8080/x5/UI2/portal/Oauth2.j?username=demo'</script>");
            }else{
                res.end("userid:" + userID);
            }
        });
    }
}

/**
 * 验证
 * URL:http://x5.justep.com/wechat/urlCheck
 *  Token:chJY
 * EncodingAESKey:ewx7yEOFP97pqImLcg9plXEA9BvbGo85oixy3eXtoih
 *
 收到请求:
 /wechat/urlCheck?msg_signature=f0e68c519aef9fb044b5470b6c71ad1cb0dd8520&timestamp=1413166784&nonce=2077967001&echostr=gxVuKaP%2FZQ6Yd09WeQzSAsyaEsyT3CwgODs%2F7Kg6QUfn6iXxuUrCeCPF7EkwJviylOo8qOaMFuDY%2FJbM8vCsqQ%3D%3D
 /wechat/urlCheck?
 msg_signature=f0e68c519aef9fb044b5470b6c71ad1cb0dd8520
 &timestamp=1413166784&
 nonce=2077967001&
 echostr=gxVuKaP%2FZQ6Yd09WeQzSAsyaEsyT3CwgODs%2F7Kg6QUfn6iXxuUrCeCPF7EkwJviylOo8qOaMFuDY%2FJbM8vCsqQ%3D%3D
 **/

Weixin.prototype.checkSignature = function(req,res) {
    // 获取校验参数
    this.signature = req.query.msg_signature,
    this.timestamp = req.query.timestamp,
    this.nonce = req.query.nonce,
    this.echostr = req.query.echostr;
    //signature,timestamp,nonce,token,echostr
    var isLegel = helper.isLegel(this.signature,this.timestamp,this.nonce,Token,this.echostr);
    if(isLegel){
        console.log('\n url check 成功' + req.url);
        res.writeHead(200, {'Content-Type': 'text/plain' });
        res.end(helper.decryptMessage(this.echostr,corpid,EncodingAESKey));
    }else{
        console.log('\n url check 失败' + req.url);
        res.writeHead(200, {'Content-Type': 'text/plain' })
        res.end("error");
    }
};


/**
 * <xml>
 <ToUserName><![CDATA[toUser]]</ToUserName>
 <AgentID><![CDATA[toAgentID]]</AgentID>
 <Encrypt><![CDATA[msg_encrypt]]</Encrypt>
 </xml>
 */
Weixin.prototype.onMessage = function(req,res) {
    var self = this;
    var bodyparserFunc = bodyParser.text({ type: 'text/xml' });
    bodyparserFunc(req,res,function(){
        self._preParam(req, res,self._next);
    });
};

var events = {
    text:function(req, res, next){
        console.log('\n收到文本类型消息:' + req.body.content);
        next();
    }
    ,image:function(req, res, next){
        next();
    }
    ,voice:function(req, res, next){
        next();
    }
    ,video:function(req, res, next){
        next();
    }
    ,location:function(req, res, next){
        next();
    }
    ,event:{
        subscribe:function(req, res, next){
            /**
             * {
                 "tousername":"wx44d77f4bc582313e",
                 "fromusername":"wsh_justep",
                 "createtime":"1413189235",
                 "msgtype":"event",
                 "agentid":"2",
                 "event":"subscribe",
                 "eventkey":""
             * }
             */
            console.log('\n收到订阅类型事件:' + req.body.content);
            next();
        }//订阅
        ,unsubscribe:function(req, res, next){next();}//取消订阅
        ,click:function(req, res, next){next();}//
        ,view:function(req, res, next){next();}//
        ,location:function(req, res, next){next();}//
    }
}


Weixin.prototype._msgReplier = function(req,res,next) {
    var _type=req.body["msgtype"];
    var _func = events[_type];
    if(typeof _func === "function"){
        req.wechat = req.wechat ||{};
        req.wechat.agentid = req.body.agentid;
        req.wechat.msgid = req.body.msgid;
        res.replay = new replay(req, res);
        debugger;
        if(res.replay.text){
            res.replay.text();
            _func(req, res, next);
        }else{
            _func(req, res, next);
        }
    }else{
        next();
    }
};


Weixin.prototype._next = function(error){
    console.log("\n 微信响应结束，错误：" + error);
};

Weixin.prototype._preParam = function(req,res,next){
    var self = this;
    console.log("\n 收到post请求：" + req.chunks.toString());
    helper.xmlToJson(req.chunks.toString(),function(err){
        next(err)
    },function(_body){
        req.body = _body;
        var _message= helper.decryptMessage(req.body["encrypt"],corpid,EncodingAESKey);
        helper.xmlToJson(_message,function(err){
            next(err);
        },function(data){
            console.log("\n解密后消息正文是：" + JSON.stringify(data));
            req.body = data;
            self._msgReplier(req,res,next);
        });
    });
};

module.exports = new Weixin();